import type { UserResult } from "@/api/user";
import { getLogin } from "@/api/user";
import { routerArrays } from "@/layout/types";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { removeToken, setToken, userKey, type DataInfo } from "@/utils/auth";
import { storageLocal } from "@pureadmin/utils";
import { defineStore } from "pinia";
import type { userType } from "./types";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 用户名
    username: storageLocal().getItem<DataInfo<number>>(userKey)?.username ?? "",
    // 页面级别权限
    roles: storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? []
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then(data => {
            if (data) {
              // data.data?.permissionData.splice(-1);
              setToken(data);
              resolve(data);
              let GlobalState = {
                token: data.token || "",
                // userInfo
                userInfo: "",
                // element组件大小
                assemblySize: "default",
                // 是否显示头部 侧边
                isShowHeaderAsside: false,
                uacHeaderHeight: 40,
                uacFontSize: 14,
                // themeConfig
                themeConfig: {
                  // 当前页面是否全屏
                  maximize: false,
                  // 布局切换 ==>  纵向：vertical | 经典：classic | 分栏：columns
                  layout: "vertical",
                  // 默认 primary 主题颜色
                  primary: "#3b82f6",
                  // 深色模式
                  isDark: false,
                  // 灰色模式
                  isGrey: false,
                  // 色弱模式
                  isWeak: false,
                  // 折叠菜单
                  isCollapse: false,
                  // 面包屑导航
                  breadcrumb: true,
                  // 面包屑导航图标
                  breadcrumbIcon: false,
                  // 标签页
                  tabs: false,
                  // 标签页图标
                  tabsIcon: true,
                  // 页脚
                  footer: false
                }
              };
              localStorage.setItem("GlobalState", JSON.stringify(GlobalState));
              localStorage.setItem("targetSysName", "IFP");
              localStorage.setItem("targetSysCode", "sys-ifp");
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      removeToken();
      storageLocal().removeItem("className");
      storageLocal().removeItem("GlobalState");
      storageLocal().removeItem("hidenMenu");
      storageLocal().removeItem("async-routes");
      storageLocal().removeItem("permissionList");
      storageLocal().removeItem("userInfo");
      storageLocal().setItem("responsive-tags", []);
      storageLocal().removeItem("targetSysName");
      storageLocal().removeItem("targetSysCode");
      storageLocal().removeItem("facCode");
      storageLocal().removeItem("facList");
      storageLocal().removeItem("classList");
      storageLocal().removeItem("pmsPermission");
      useMultiTagsStoreHook().ISTOTICED(false);
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      // router.push("/login");
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
